/*
 * Virus.cxx
 *
 *  Created on: 10:09:49 PM Oct 15, 2012
 *  Author: Pallab
 *
 * "I have not failed, I have just found 10000 ways that won't work.
 */

#include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <fstream>
#include <string>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <functional>
#include <bitset>
#include <iomanip>

#include <ctime>
#include <cassert>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <climits>
#include <cstring>
#include <cstdlib>

using namespace std;

#define foR(i1,st,ed) for(int i1 = st , j1 = ed ; i1 < j1 ; ++i1 )
#define fo(i1,ed) foR( i1 , 0 , ed )
#define foE(i1,st,ed) foR( i1, st, ed+1 )
#define foit(i, x) for (typeof((x).begin()) i = (x).begin(); i != (x).end(); i++)
#define bip system("pause")
#define Int long long
#define pb push_back
#define SZ(X) (int)(X).size()
#define LN(X) (int)(X).length()
#define mk make_pair
#define SET( ARRAY , VALUE ) memset( ARRAY , VALUE , sizeof(ARRAY) )
#define line puts("")

inline void wait(double seconds) {
	double endtime = clock() + (seconds * CLOCKS_PER_SEC);
	while (clock() < endtime) {
		;
	}
}
#define T int
inline T fastIn() {
	register char c = 0;
	register T a = 0;
	while (c < 33)
		c = getchar();
	while (c > 33) {
		a = (a * 10) + (c - '0');
		c = getchar();
	}
	return a;
}
const int LIMIT = 100001;
const int MX = 1000;

int number_count1, number_count2;
int numbers1[MX], numbers2[MX];
vector<int> adj[LIMIT];
inline void read() {
	fo(i,LIMIT)
		adj[i].clear();

	number_count1 = fastIn();
	fo(i,number_count1)
		numbers1[i] = fastIn();

	number_count2 = fastIn();
	fo(i,number_count2)
		adj[fastIn()].pb(i);
}
inline int bsearch(int num, int need) {
	int sz = SZ(adj[num]);
	if (sz < 1)
		return -1;

	int indx = lower_bound(adj[num].begin(), adj[num].end(), need)
			- adj[num].begin();
	if (adj[num][indx] < need)
		++indx;
	if (indx >= sz)
		return -1;
	return adj[num][indx];
}
int dp[1000][1000];
int go(int pos1, int pos2, int k) {
	if (pos1 >= number_count1||pos2 >= number_count2) {
		return 0;
	}
	int &bst = dp[pos1][pos2];
	if (bst != -1)
		return bst;
	bst = 0;
	//--------------------
	int prv = numbers1[k];
	if (numbers1[pos1] > prv) {
		int nxt_indx = bsearch(numbers1[pos1], pos2);
		if (nxt_indx != -1) {
			bst = max(bst, go(pos1 + 1, nxt_indx + 1, pos1) + 1);
		}
	}
	bst = max(bst, go(pos1 + 1, pos2, k));
	return bst;
}

inline void proc() {
	numbers1[number_count1]=-1;
	//--------------------------------
	SET(dp, -1);
	cout << go(0, 0, number_count1) << '\n';
}
int main() {
	int kase = 1;
#if defined( xerxes_pc )
	if (!freopen("in1", "r", stdin))
		puts("error opening file Virus/in1 "), assert(0);
	kase = 1;
#endif
	kase = fastIn();
	fo(i,kase)
	{
		read();
		proc();
	}
	return 0;
}

